package common.netty.client.codec;

import com.alibaba.fastjson.JSON;
import common.RpcResponse;
import common.serializer.Serializer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public class ClientProtocolDecoder extends MessageToMessageDecoder<ByteBuf> {

    private static final int LENGTH_SIZE = 2;

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> out) throws Exception {
        //直接用byteBuf会报 io.netty.handler.codec.DecoderException: java.lang.UnsupportedOperationException: direct buffer错误
        log.info("server 接受数据 长度为:{}", byteBuf.readableBytes());
        if(byteBuf.readableBytes() > LENGTH_SIZE) {
            byteBuf.readInt();
            ByteBuf tmpBuf = byteBuf.readBytes(byteBuf.readableBytes());
            byte[] bs = new byte[tmpBuf.readableBytes()];
            tmpBuf.readBytes(bs);
            RpcResponse responseMessage = new RpcResponse();
            responseMessage = responseMessage.deserialize(RpcResponse.class, bs);

            log.info("Client 反序列化完成:{}, byteBuf的长度是:{}", JSON.toJSON(responseMessage), byteBuf.readableBytes());
            out.add(responseMessage);
        }
    }
}
